import { Sharelink } from '@/types/share-link';
import { create } from 'zustand';
import { getItem, removeItem, setItem } from '@/utils/storage';
import { StorageEnum } from '@/types/enum';
import shareLinkSvc from '@/api/services/sharelink';
type ShareLinkStore = {
  shareLinks: Sharelink[];
  page: number;
  pageSize: number;
  total: number;
  loading: boolean;
  // 使用 actions 命名空间来存放所有的 action
  actions: {
    setPage: (page: number) => void;
    setPageSize: (pageSize: number) => void;
    getShareLinks: (appId: string) => Promise<void>;
    setShareLink: (shareLinks: Sharelink[]) => void;
  };
};

const useShareLinkStore = create<ShareLinkStore>((set, get) => ({
  shareLinks: [],
  page: 1,
  pageSize: 10,
  loading: false,
  total: 0,
  actions: {
    setShareLink: (shareLinks) => {
      set({ shareLinks });
    },
    setPage: (page) => {
      set({ page });
    },
    setPageSize: (pageSize) => {
      set({ pageSize });
    },
    async getShareLinks(app_id: string) {
      set({ loading: true });
      try {
        const page = get().page;
        const page_size = get().pageSize;
        const { list, total } = await shareLinkSvc.getShareLinkList({ page, page_size, app_id });
        set({ shareLinks: list, total });
      } catch (error) {
        console.error(error);
      } finally {
        set({ loading: false });
      }
    },
  },
}));

export const useShareLink = () => useShareLinkStore((state) => state);
export const useShareLinkActions = () => useShareLinkStore((state) => state.actions);
